package com.example.lpc_.controller;

import com.example.lpc_.mapper.UserMapper;
import com.example.lpc_.pojo.dto.UserLoginDTO;
import com.example.lpc_.pojo.dto.UserRegDTO;
import com.example.lpc_.pojo.entity.User;
import com.example.lpc_.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @BelongsProject: second_market
 * @BelongsPackage: com.example.lpc_.controller
 * @Author: dianye
 * @CreateTime: 2022-10-21  20:49
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/user/reg")
    public int userReg(@RequestBody UserRegDTO userDTO) {
        System.out.println("注册用户信息:user = " + userDTO);
        UserVO u=mapper.selectByUsername(userDTO.getUsername());
        if(u!=null){
            return 2;
        }
        User  user=new User();
        /*把DTO的属性赋值给实体类*/
        BeanUtils.copyProperties(userDTO, user);
        user.setCreated(new Date());
        /*默认注册的都是用户*/
        user.setPower(1);
        mapper.insert(user);
        return 1;
    }
    @RequestMapping("/user/login")
    public int userLogin(@RequestBody UserLoginDTO userDTO, HttpSession session, HttpServletResponse response) {
        System.out.println("登录用户信息userDTO = " + userDTO );
        UserVO u=mapper.selectByUsername(userDTO.getUsername());
        if(u!=null){
            if(u.getPassword().equals(userDTO.getPassword())) {
                if(userDTO.getRem()){
                    Cookie c1=new Cookie("username", userDTO.getUsername());
                    Cookie c2=new Cookie("password", userDTO.getPassword());
                    /*保存一周*/
                    c1.setMaxAge(60*60*24*7);
                    c2.setMaxAge(60*60*24*7);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                /*把当前登录的用户对象保存到Session里面*/
                session.setAttribute("user",u);
                return 1;
            }
            return 3;
        }
       return 2;
    }
    @RequestMapping("/user/currentUser")
    public UserVO currentUser(HttpSession session) {
        return (UserVO) session.getAttribute("user");
    }
    @RequestMapping("/user/logout")
    public void logout(HttpSession session) {
        session.removeAttribute("user");
    }
}
